const express = require("express");
const multer = require("multer"); // 文件上传中间件
const bodyParser = require("body-parser");
const path = require("path");
const fs = require("fs");
const dayjs = require("dayjs");

// 设置multer存储文件的配置
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "uploads/");
  },
  filename: function (req, file, cb) {
    // 解决中文名乱码的问题
    // file.originalname = Buffer.from(file.originalname, "latin1").toString("utf8");
    cb(null, `${dayjs().format("YYYYMMDD_HHmmss")}-${file.originalname}`);
  },
});

// 创建multer实例
const upload = multer({ storage });
const app = express();
// 设置静态资源目录，用于公开可下载的文件
app.use("/downloads", express.static(path.join(__dirname, "/uploads")));

app.post("/api/upload", upload.single("file"), (req, res) => {
  try {
    // 如果文件上传成功，req.file将会包含文件信息
    if (req.file) {
      console.log("Uploaded File11:", req.file);
      res.status(200).json({ code: 0, retdata: { filePath: req.file.path } });
    } else {
      res.status(400).json({ error: "No file was uploaded" });
    }
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: "An error occurred while uploading the file." });
  }
});

app.get("/api/download", (req, res) => {
  const filename = req.query.filename;
  // const filePath = path.join(__dirname, "uploads", filename);
  console.log(`${req.protocol}://${req.get("host")}`);
  const downloadUrl = `${req.protocol}://${req.get("host").replace("9000", "3000")}/downloads/${filename}`;
  res.json({ url: downloadUrl });

  // 检查文件是否存在并发送文件
  // res.download(filePath, filename, (err) => {
  //   if (err) {
  //     res.status(404).send("File not found");
  //   } else {
  //     console.log("File sent");
  //   }
  // });

  // 对文件名进行URL编码
  // const encodedFileName = encodeURIComponent(filename);

  // res.set({
  //   "Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  //   "Content-Disposition": `attachment; filename*=UTF-8''${encodedFileName}`,
  // });

  // 发送文件内容
  // fs.createReadStream(filePath).pipe(res);

  // 设置响应头以指示浏览器下载文件而不是显示内容
  // res.setHeader("Content-Type", "application/octet-stream");
  // res.setHeader("Content-Disposition", 'attachment; filename="' + encodedFileName + '"');
});

app.listen(3000, () => console.log("Server started on port 3000"));
